package cn.gdrj.est.controller;

import cn.gdrj.est.common.controller.BaseController;
import cn.gdrj.est.constants.Constants;
import cn.gdrj.est.dto.CommonResult;
import cn.gdrj.est.entity.Users;
import cn.gdrj.est.service.TokenService;
import cn.gdrj.est.service.UsersService;
import cn.gdrj.est.util.ResultUtil;
import cn.gdrj.est.util.WechatLoginProperties;
import cn.gdrj.est.vo.TokenVO;
import cn.gdrj.est.vo.UsersVO;
import cn.hutool.db.handler.HandleHelper;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/user")
public class UserController extends BaseController {

    //@Value("${oauth2.wechat.codeUrl}")
    //private String codeUrl;
    @Autowired
    private WechatLoginProperties wechatLoginProperties;
    @Autowired
    private UsersService usersService;
    @Autowired
    private TokenService tokenService;

    @GetMapping("/login/wechat")
    public void wechatLogin() throws IOException {
        String url=wechatLoginProperties.getFullCodeUrl();
        response.sendRedirect(url);
    }

    @GetMapping("/login/wechatcallback")
    public void wechatCall(String code,String state) throws IOException {
        // 发送获取accessToken的请求
        String getAccessTokenURL = wechatLoginProperties.getFullAccessTokenURL(code);
        String accessTokenJsonString = HttpUtil.get(getAccessTokenURL);
        JSONObject accessTokenJsonObj = JSONObject.parseObject(accessTokenJsonString);

        // 获取access_token和openid
        String accessToken = accessTokenJsonObj.getString("access_token");
        String openid = accessTokenJsonObj.getString("openid");

        // 根据openId查询用户是否已经存在
        Users users = usersService.findByOpenId(openid);

        // 如果不存在，需要获取用户信息，进行自动注册
        if(users == null){
            String getUserInfoURL = wechatLoginProperties.getFullUserInfoURL(accessToken,openid);
            String userInfoJsonString = HttpUtil.get(getUserInfoURL);
            JSONObject userInfoJsonObj = JSONObject.parseObject(userInfoJsonString);

            users = new Users();
            users.setUserName(userInfoJsonObj.getString("nickname"));
            users.setSex(userInfoJsonObj.getInteger("sex"));
            users.setIsAuthentication(Constants.EST_NOT);
            users.setFaceUrl(userInfoJsonObj.getString("headimgurl"));
            users.setOpenId(openid);
            Date createdTime = new Date();
            users.setCreatedTime(createdTime);
            users.setUpdatedTime(createdTime);
            users.setIsDelete(Constants.EST_NOT);

            // set ...
            usersService.register(users);
        }

        // 登录
        TokenVO tokenVO = tokenService.generateToken(users);
        tokenService.saveToken(tokenVO.getToken(),users);

        // 返回登录成功的结果
        Map<String,String> tokenMap = new HashMap<>();
        tokenMap.put("token",tokenVO.getToken());
        tokenMap.put("userInfo",users.getUserName());
        String jsonString = JSON.toJSONString(tokenMap);
        String encodeJsonString = URLEncoder.encode(jsonString, "utf-8");
        response.sendRedirect(wechatLoginProperties.getLoginSuccessUrl()+encodeJsonString);
    }

    @PostMapping("/login/sms")
    public CommonResult<TokenVO> loginBySms(@RequestParam String phone,
                                            @RequestParam String sms){
        Users users = usersService.loginBySms(phone,sms);

        TokenVO tokenVO = tokenService.generateToken(users);
        tokenService.saveToken(tokenVO.getToken(),users);

        return ResultUtil.success(tokenVO);
    }

    @GetMapping("info")
    public CommonResult getUserInfo(){
        String token = request.getHeader("token");
        Users users = tokenService.getUserInfoByToken(token);
        UsersVO usersVO = new UsersVO();
        BeanUtils.copyProperties(users,usersVO);
        usersVO.setToken(token);
        return ResultUtil.success(usersVO);
    }
}
